package com.qcby.exception;

import java.sql.SQLIntegrityConstraintViolationException;

import org.springframework.dao.DataAccessException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.qcby.Constants;
import com.qcby.model.resp.RespEntity;

@ControllerAdvice
public class MyExceptionHandler {

    // 处理自定义异常
    @ExceptionHandler(MyRuntimeException.class)
    @ResponseBody
    public RespEntity serviceExe(MyRuntimeException se) {
        se.printStackTrace();
        // 出现异常之后,返回异常的RespEntity
        return RespEntity.errorNoData(se.getFlag(), se.getMessage());
    }


    // 处理数据库异常（包括 SQLIntegrityConstraintViolationException）
    @ExceptionHandler(DataAccessException.class)
    @ResponseBody
    public RespEntity handleDatabaseException(DataAccessException ex) {
        ex.printStackTrace();
        // 判断是否为违反唯一约束的错误
        if (ex.getCause() instanceof SQLIntegrityConstraintViolationException) {
            return RespEntity.errorNoData(Constants.FLAG_500, "Duplicate entry for key: " + ex.getCause().getMessage());
        }
        return RespEntity.errorNoData(Constants.FLAG_500, "Database error: " + ex.getMessage());
    }

    // 处理参数异常
    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseBody
    public RespEntity handleIllegalArgumentException(IllegalArgumentException iae) {
        iae.printStackTrace();
        return RespEntity.errorNoData(Constants.FLAG_400, "请求参数异常: " + iae.getMessage());
    }

    // 处理其他未知异常
//    @ExceptionHandler(Exception.class)
//    @ResponseBody
//    public RespEntity handleUnKnowenException(Exception e) {
//        return RespEntity.errorNoData(Constants.FLAG_501, "服务端未知异常！: " + e.getMessage());
//    }

    // 处理其他未知异常
    @ExceptionHandler(NullPointerException.class)
    @ResponseBody
    public RespEntity handleNullPointerException(NullPointerException npe) {
        npe.printStackTrace();
        return RespEntity.errorNoData(Constants.FLAG_500, "空指针异常！: " + npe.getMessage());
    }
}
